// pages/search/search.js
import request from '../../utils/request.js';
import PubSub from 'pubsub-js'
let isSend = false // 搜索节流
Page({

    /**
     * 页面的初始数据
     */
    data: {
        placeholderContent: '',
        hotList: [],
        searchContent: '',// 用户输入表单项
        searchList: [], // 模糊匹配
        historyList: [],
        searchResult: [],
        type: '',
        index: 0, // 点击音乐的下标(切换上下首)
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getInitData()
        this.gethistoryList()
         // 下一首订阅
         PubSub.subscribe('switchType', (msg, type) => {
            // console.log(msg, type)
            let {searchResult, index} = this.data
            if (type === 'pre') {
                (index === 0) && (index = searchResult.length)
                index -= 1
            }else{
                (index === searchResult.length -1) && (index = -1)
                index += 1
            }
            // 更新下标
            this.setData({
                index
            })
            // 找到歌曲
            let musicId = searchResult[index].id
            // 回传给songDetail
            PubSub.publish('musicId', musicId)
        })
    },
    // 默认搜索信息
    async getInitData() {
        const result = await request('/search/default')
        const hotListData = await request('/search/hot/detail');
        // console.log(result)
        this.setData({
            placeholderContent: result.data.showKeyword,
            hotList: hotListData.data
        })
    },
    // input内容改变
    handleInputChange(event) {
        // console.log(event)
        this.setData({
            searchContent: event.detail.value.trim()
        })
        // 获取模糊匹配请求
        if (isSend) {
            return
        }
        isSend = true
        this.getSearchList()
        setTimeout(() => {
            this.getSearchList()
            isSend = false
        }, 300)
    },
    // 模糊搜索请求列表
    async getSearchList() {
        // 无搜索内容时清空列表
        if(!this.data.searchContent) {
            this.setData({
                searchList: []
            })
            return
        }
        const {searchContent, historyList} = this.data
        const {result} = await request('/search', {keywords: searchContent, limit: 10})
        this.setData({
            searchList: result.songs,
            type: 1
        })
        // 记录搜索记录
        if(historyList.indexOf(searchContent) !== -1){
            historyList.splice(historyList.indexOf(searchContent), 1)
        }
        historyList.unshift(searchContent)
        this.setData({
            historyList
        })
        // 本地存储
        wx.setStorageSync('historyList', historyList)
    },
    // 点击联想搜索列表item
    searchItem(event) {
        // console.log(event)
        this.setData({
            searchContent: event.currentTarget.dataset.item.name,
            searchList: []
        })
    },
    // 取消搜索
    clearSearchContent() {
        this.setData({
            searchList: [],
            searchContent: '',
            searchResult: [],
            type: ''
        })
    },
    // 获取历史记录
    gethistoryList() {
        const historyList = wx.getStorageSync('historyList')
        if(historyList) {
            this.setData({
                historyList
            })
        }
    },
    // 删除历史记录
    deleteSearchHistory() {
        wx.showModal({
          content: '确认删除吗',
          success: (res) => {
              if(res.confirm) {
                  this.setData({
                      historyList: []
                  })
                  wx.removeStorageSync('historyList')
              }
          }
        })
    },
    // 获取搜索结果
    async handleInputBlur() {
       if (this.data.searchContent.trim() !== ''){
        const {result} = await request('/search', {keywords: this.data.searchContent})
        console.log(result)
        this.setData({
            searchResult: result.songs,
            type: 2
        })
       }
    },
    // 点击历史记录搜索
    historyItemSearch(event) {
        console.log(event)
        this.setData({
            searchContent: event.currentTarget.dataset.item
        })
        this.handleInputBlur()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})